<template>
  <div>
    <el-tree-select
        :multiple="multiple"
        :treeProps="deptProps"
        :data="treeData"
        :checkedKeys="selectValue"
        @nodeClickChange="changeSelectNode"
        @onCheckedChange="checkedChangeNode"
    >
    </el-tree-select>
  </div>
</template>

<script>
import ElTreeSelect from "@/components/common/ElTreeSelect";
import {loadAll} from "@/api/sys/deptApi";
import treeUtils from "@/utils/treeUtils";
import ElColumnDept from "@/components/start-boot/columns/ElColumnDept";

export default {
  name: "el-dept-tree-select",
  columnComponents: ElColumnDept.name,
  components: {
    ElTreeSelect
  },
  props: {
    value: {
      type: String,
      default: null,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: null,
    },

  },
  watch: {
    value(val) {
      this.calculationTreeSelectValue()
    }
  },
  data() {
    return {
      selectValue: [],
      treeData: null,
      deptProps: {
        label: 'name',
      }
    }
  },
  created() {
    this.initAllTree();
    this.calculationTreeSelectValue();
  },

  methods: {
    initAllTree() {
      loadAll().then(res => {
        let data = res.data.data;
        this.treeData = treeUtils.listToTree(data)
      })
    },
    calculationTreeSelectValue() {
      if (!this.value) {
        this.selectValue = []
        return
      }
      let temp = [];
      if (this.value.indexOf(",") < 0) {
        temp.push(this.value)
      } else {
        temp = this.value.split(",")
      }
      this.selectValue = temp;
    },
    changeSelectNode(key, data, node) {
      this.$emit("input", data.id)
      this.$emit("change", data.id)
    },
    checkedChangeNode(keys, node) {
      this.$emit("input", keys.join(","))
      this.$emit("change", keys.join(","))
    }
  }
}
</script>

<style scoped>

</style>
